import {defineStore} from 'pinia'
import LoginApi from "@/common/api/login.js";
import {TokenUtil} from "@lowcode/jpaas-base-lib";

export default defineStore('user', {
    state: () => {//必须是箭头函数
        return {
            passwordMode: 'default',//密码模式 (default 默认模式，md5 md5加密模式)
            token:"",
            user:"",
            siteName:"",
            //用户是否首次登录
            isFirstLogin: false,
        }
    },
    //类似组件的computed,有缓存的功能
    getters: { },
    //类似组件的methods  封装业务逻辑  修改state
    actions: {
        setIsFirstLogin(isFirstLogin){
            this.isFirstLogin = isFirstLogin;
        },
        setPasswordMode(passwordMode){
            this.passwordMode = passwordMode ;
        },
        setSiteName(siteName){
            this.siteName = siteName ;
        },
        setToken(token){
            this.token = token ;
        },
        setUser(user){
            this.user = user ;
        },
        // 登录
        async Login(userInfo,callback) {
            try {
                LoginApi.login(userInfo).then(res => {
                    if(res.success){
                        const {accessToken,user} = res.data;
                        if(accessToken && accessToken.access_token){
                            TokenUtil.setToken(accessToken.access_token);
                            this.setToken(accessToken.access_token);
                        }
                        this.setUser(user || '')
                        this.setIsFirstLogin(user.isFirstLogin === 'YES');
                        callback && callback(res)
                    }
                    else{
                        callback && callback("",res)
                    }
                }).catch(error => {
                    callback && callback("",error)
                })
            } catch (error) {
                callback && callback("",error)
            }
        },
        //根据第三方授权code自动登录
        AutoLoginByCode(params, callback) {
            LoginApi.autoLoginByCode(params).then(res => {
                const result = res.data
                //请求返回体加密时：token = result.value
                let token = result.access_token || result.value;
                if(token){
                    TokenUtil.setToken(token);
                    this.setToken(token);
                }
                if(callback){
                    callback(res)
                }
            }).catch(error => {
                if(callback){
                    callback("",error)
                }
            })
        },
    }
})
